package com.esayread.ui.reading

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.pager.PagerState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Bookmark
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.filled.List
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import androidx.activity.ComponentActivity
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import androidx.compose.ui.viewinterop.AndroidView
import android.webkit.WebView
import android.webkit.WebViewClient
import com.esayread.data.Book
import com.esayread.data.BookFormat
import com.esayread.reader.BookReader
import com.esayread.reader.BookContent
import com.esayread.reader.Chapter
import com.esayread.reader.ReadingProgressManager
import com.esayread.ui.theme.EsayReadTheme
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import android.util.Log
import com.google.gson.Gson
import com.esayread.reader.TocItem

@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)
@Composable
fun ReadingScreen(
    navController: NavController,
    bookJson: String
) {
    val context = LocalContext.current
    val view = LocalView.current
    val book = remember {
        Gson().fromJson(bookJson, Book::class.java)
    }
    
    // 设置沉浸式模式
    LaunchedEffect(Unit) {
        val window = (context as ComponentActivity).window
        WindowCompat.setDecorFitsSystemWindows(window, false)
        val controller = WindowInsetsControllerCompat(window, view)
        controller.hide(WindowInsetsCompat.Type.systemBars())
        controller.systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
    }
    
    // 退出时恢复系统栏
    DisposableEffect(Unit) {
        onDispose {
            val window = (context as ComponentActivity).window
            val controller = WindowInsetsControllerCompat(window, view)
            controller.show(WindowInsetsCompat.Type.systemBars())
            WindowCompat.setDecorFitsSystemWindows(window, true)
        }
    }
    
    var isToolbarVisible by remember { mutableStateOf(false) }
    var currentProgress by remember { mutableStateOf(0.0f) }
    var bookContent by remember { mutableStateOf<BookContent?>(null) }
    var isLoading by remember { mutableStateOf(true) }
    var errorMessage by remember { mutableStateOf<String?>(null) }
    var currentChapterIndex by remember { mutableStateOf(0) }
    var currentChapterPosition by remember { mutableStateOf(0) }
    var showTableOfContents by remember { mutableStateOf(false) }
    
    val bookReader = remember { BookReader(context) }
    val progressManager = remember { ReadingProgressManager(context) }
    
    // 分页状态 - 每章作为一页
    val pagerState = rememberPagerState(pageCount = { bookContent?.chapters?.size ?: 0 })
    
    // 加载电子书内容
    LaunchedEffect(book) {
        try {
            isLoading = true
            errorMessage = null
            
            // 读取电子书内容
            val content = bookReader.readBook(book.filePath, book.format)
            bookContent = content
            
            // 加载阅读进度
            val savedProgress = progressManager.getProgress(book.filePath)
            if (savedProgress != null) {
                currentChapterIndex = savedProgress.chapterIndex
                currentChapterPosition = savedProgress.chapterPosition
                currentProgress = savedProgress.progressPercentage / 100f
                Log.d("ReadingScreen", "Loaded progress: chapter ${savedProgress.chapterIndex}, position ${savedProgress.chapterPosition}")
            }
            
            isLoading = false
        } catch (e: Exception) {
            Log.e("ReadingScreen", "Error loading book: ${e.message}", e)
            errorMessage = e.message ?: "加载电子书失败"
            isLoading = false
        }
    }
    
    // 预加载相邻章节
    LaunchedEffect(pagerState.currentPage, bookContent) {
        bookContent?.let { content ->
            val currentPage = pagerState.currentPage
            
            // 预加载下一章
            if (currentPage + 1 < content.chapters.size) {
                val nextChapter = content.chapters[currentPage + 1]
                if (nextChapter.content.isEmpty() && nextChapter.isHtml) {
                    try {
                        bookReader.loadChapterContent(nextChapter)
                    } catch (e: Exception) {
                        Log.w("ReadingScreen", "Failed to preload next chapter: ${e.message}")
                    }
                }
            }
            
            // 预加载上一章
            if (currentPage - 1 >= 0) {
                val prevChapter = content.chapters[currentPage - 1]
                if (prevChapter.content.isEmpty() && prevChapter.isHtml) {
                    try {
                        bookReader.loadChapterContent(prevChapter)
                    } catch (e: Exception) {
                        Log.w("ReadingScreen", "Failed to preload previous chapter: ${e.message}")
                    }
                }
            }
        }
    }
    
    // 同步pager状态和章节索引
    LaunchedEffect(pagerState.currentPage) {
        currentChapterIndex = pagerState.currentPage
        currentChapterPosition = 0 // 翻页时重置章节内位置
        
        // 更新进度
        bookContent?.let { content ->
            val progress = (currentChapterIndex + 1).toFloat() / content.chapters.size
            currentProgress = progress
            
            // 翻页后立即保存阅读进度
            val globalPosition = content.getGlobalPosition(currentChapterIndex, currentChapterPosition)
            val totalCharacters = content.getTotalCharacters()
            kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.IO).launch {
                progressManager.saveProgress(
                    bookPath = book.filePath,
                    chapterIndex = currentChapterIndex,
                    chapterPosition = currentChapterPosition,
                    globalPosition = globalPosition,
                    totalCharacters = totalCharacters
                )
            }
        }
    }
    
    // 当章节索引改变时，更新pager状态
    LaunchedEffect(currentChapterIndex) {
        if (pagerState.currentPage != currentChapterIndex) {
            pagerState.animateScrollToPage(currentChapterIndex)
        }
    }
    
    // 自动隐藏工具栏
    LaunchedEffect(isToolbarVisible) {
        if (isToolbarVisible) {
            delay(3000) // 3秒后自动隐藏
            isToolbarVisible = false
        }
    }
    
    // 保存阅读进度
    val saveProgress = {
        bookContent?.let { content ->
            val globalPosition = content.getGlobalPosition(currentChapterIndex, currentChapterPosition)
            val totalCharacters = content.getTotalCharacters()
            
            // 使用协程保存进度
            kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.IO).launch {
                progressManager.saveProgress(
                    bookPath = book.filePath,
                    chapterIndex = currentChapterIndex,
                    chapterPosition = currentChapterPosition,
                    globalPosition = globalPosition,
                    totalCharacters = totalCharacters
                )
            }
        }
    }
    
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.White)
    ) {
        when {
            isLoading -> {
                // 加载中状态
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    Column(
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        CircularProgressIndicator()
                        Spacer(modifier = Modifier.height(16.dp))
                        Text(
                            text = "正在加载《${book.title}》...",
                            style = MaterialTheme.typography.bodyMedium
                        )
                    }
                }
            }
            
            errorMessage != null -> {
                // 错误状态
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    Column(
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        Text(
                            text = "加载失败",
                            style = MaterialTheme.typography.headlineSmall,
                            color = MaterialTheme.colorScheme.error
                        )
                        Spacer(modifier = Modifier.height(8.dp))
                        Text(
                            text = errorMessage!!,
                            style = MaterialTheme.typography.bodyMedium,
                            textAlign = TextAlign.Center
                        )
                        Spacer(modifier = Modifier.height(16.dp))
                        Button(
                            onClick = { navController.popBackStack() }
                        ) {
                            Text("返回")
                        }
                    }
                }
            }
            
            bookContent != null -> {
                // 左右翻页阅读区域
                HorizontalPager(
                    state = pagerState,
                    modifier = Modifier
                        .fillMaxSize()
                        .clickable {
                            isToolbarVisible = !isToolbarVisible
                        }
                ) { pageIndex ->
                    ReadingPageContent(
                        bookContent = bookContent!!,
                        chapterIndex = pageIndex,
                        modifier = Modifier.fillMaxSize()
                    )
                }
            }
        }
        
        // 顶部工具栏
        AnimatedVisibility(
            visible = isToolbarVisible,
            enter = slideInVertically(initialOffsetY = { -it }),
            exit = slideOutVertically(targetOffsetY = { -it }),
            modifier = Modifier.align(Alignment.TopCenter)
        ) {
            TopAppBar(
                title = {
                    Text(
                        text = book.title,
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis
                    )
                },
                navigationIcon = {
                    IconButton(
                        onClick = { navController.popBackStack() }
                    ) {
                        Icon(
                            imageVector = Icons.Default.ArrowBack,
                            contentDescription = "返回"
                        )
                    }
                },
                actions = {
                    // 目录按钮
                    if (bookContent?.tableOfContents?.isNotEmpty() == true) {
                        IconButton(onClick = { showTableOfContents = true }) {
                            Icon(
                                imageVector = Icons.Default.List,
                                contentDescription = "目录"
                            )
                        }
                    }
                    IconButton(onClick = { /* TODO: 书签功能 */ }) {
                        Icon(
                            imageVector = Icons.Default.Bookmark,
                            contentDescription = "书签"
                        )
                    }
                    IconButton(onClick = { /* TODO: 设置功能 */ }) {
                        Icon(
                            imageVector = Icons.Default.Settings,
                            contentDescription = "设置"
                        )
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = Color.Black.copy(alpha = 0.8f),
                    titleContentColor = Color.White,
                    navigationIconContentColor = Color.White,
                    actionIconContentColor = Color.White
                )
            )
        }
        
        // 底部工具栏
        AnimatedVisibility(
            visible = isToolbarVisible,
            enter = slideInVertically(initialOffsetY = { it }),
            exit = slideOutVertically(targetOffsetY = { it }),
            modifier = Modifier.align(Alignment.BottomCenter)
        ) {
            BottomReadingToolbar(
                progress = currentProgress,
                currentChapter = if (bookContent != null && currentChapterIndex < bookContent!!.chapters.size) {
                    bookContent!!.chapters[currentChapterIndex].title
                } else "",
                totalChapters = bookContent?.chapters?.size ?: 0,
                onProgressChange = { newProgress ->
                    bookContent?.let { content ->
                        val totalCharacters = content.getTotalCharacters()
                        val targetPosition = (newProgress * totalCharacters).toInt()
                        val newChapterIndex = content.getChapterIndexByPosition(targetPosition)
                        
                        // 计算章节内位置
                        var chapterStartPosition = 0
                        for (i in 0 until newChapterIndex) {
                            chapterStartPosition += content.chapters[i].content.length
                        }
                        val newChapterPosition = targetPosition - chapterStartPosition
                        
                        currentChapterIndex = newChapterIndex
                        currentChapterPosition = newChapterPosition
                        currentProgress = newProgress
                        saveProgress()
                    }
                },
                onPreviousChapter = {
                    if (currentChapterIndex > 0) {
                        kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Main).launch {
                            pagerState.animateScrollToPage(currentChapterIndex - 1)
                        }
                    }
                },
                onNextChapter = {
                    bookContent?.let { content ->
                        if (currentChapterIndex < content.chapters.size - 1) {
                            kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Main).launch {
                                pagerState.animateScrollToPage(currentChapterIndex + 1)
                            }
                        }
                    }
                }
            )
        }
        
        // 目录对话框
        if (showTableOfContents && bookContent?.tableOfContents?.isNotEmpty() == true) {
            TableOfContentsDialog(
                tocItems = bookContent!!.tableOfContents,
                onDismiss = { showTableOfContents = false },
                onTocItemClick = { href ->
                    showTableOfContents = false
                    // 实现目录跳转 - 根据href查找对应章节
                    bookContent?.let { content ->
                        Log.d("ReadingScreen", "=== TOC Click Debug ===")
                        Log.d("ReadingScreen", "Current page: ${pagerState.currentPage}")
                        Log.d("ReadingScreen", "Total pages: ${pagerState.pageCount}")
                        Log.d("ReadingScreen", "Clicked href: $href")
                        
                        val targetChapterIndex = content.findChapterByHref(href)
                        Log.d("ReadingScreen", "Target chapter index: $targetChapterIndex")
                        
                        if (targetChapterIndex >= 0 && targetChapterIndex < pagerState.pageCount) {
                            kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Main).launch {
                                Log.d("ReadingScreen", "Animating to page: $targetChapterIndex")
                                try {
                                    pagerState.animateScrollToPage(targetChapterIndex)
                                    Log.d("ReadingScreen", "Animation completed, current page: ${pagerState.currentPage}")
                                } catch (e: Exception) {
                                    Log.e("ReadingScreen", "Animation failed: ${e.message}")
                                }
                            }
                        } else {
                            Log.w("ReadingScreen", "Invalid target index: $targetChapterIndex (pageCount: ${pagerState.pageCount})")
                        }
                    }
                }
            )
        }
    }
}

@Composable
fun ReadingContent(
    bookContent: BookContent,
    currentChapterIndex: Int,
    currentChapterPosition: Int,
    onProgressChange: (chapterIndex: Int, chapterPosition: Int, progress: Float) -> Unit,
    modifier: Modifier = Modifier
) {
    val listState = rememberLazyListState(
        initialFirstVisibleItemIndex = currentChapterIndex,
        initialFirstVisibleItemScrollOffset = currentChapterPosition
    )
    
    // 监听滚动进度
    LaunchedEffect(listState.firstVisibleItemIndex, listState.firstVisibleItemScrollOffset) {
        val chapterIndex = listState.firstVisibleItemIndex.coerceIn(0, bookContent.chapters.size - 1)
        val chapterPosition = listState.firstVisibleItemScrollOffset.coerceAtLeast(0)
        
        val globalPosition = bookContent.getGlobalPosition(chapterIndex, chapterPosition)
        val totalCharacters = bookContent.getTotalCharacters()
        val progress = if (totalCharacters > 0) {
            (globalPosition.toFloat() / totalCharacters).coerceIn(0f, 1f)
        } else 0f
        
        onProgressChange(chapterIndex, chapterPosition, progress)
    }
    
    LazyColumn(
        state = listState,
        modifier = modifier,
        verticalArrangement = Arrangement.spacedBy(0.dp)
    ) {
        // 书籍标题
        item {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(24.dp),
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = bookContent.title,
                    style = MaterialTheme.typography.headlineLarge,
                    fontWeight = FontWeight.Bold,
                    textAlign = TextAlign.Center,
                    color = MaterialTheme.colorScheme.primary
                )
            }
        }
        
        // 目录（如果有的话）
        if (bookContent.tableOfContents.isNotEmpty()) {
            item {
                Card(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 16.dp, vertical = 8.dp),
                    elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
                ) {
                    TableOfContentsRenderer(
                        tocItems = bookContent.tableOfContents,
                        onTocItemClick = { href ->
                            // TODO: 实现目录跳转
                            Log.d("ReadingContent", "TOC clicked: $href")
                        },
                        modifier = Modifier.padding(16.dp)
                    )
                }
            }
        }
        
        // 章节内容
        items(bookContent.chapters.size) { index ->
            val chapter = bookContent.chapters[index]
            
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 16.dp, vertical = 8.dp),
                elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
            ) {
                Column(
                    modifier = Modifier.padding(20.dp)
                ) {
                    // 章节标题
                    Text(
                        text = chapter.title,
                        style = MaterialTheme.typography.headlineMedium,
                        fontWeight = FontWeight.Bold,
                        textAlign = TextAlign.Center,
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(bottom = 24.dp),
                        color = MaterialTheme.colorScheme.primary
                    )
                    
                    // 章节内容 - 根据是否为HTML选择渲染方式
                    if (chapter.isHtml) {
                        HtmlContentRenderer(
                            htmlContent = chapter.content,
                            onLinkClick = { url ->
                                // TODO: 处理链接点击
                                Log.d("ReadingContent", "Link clicked: $url")
                            },
                            modifier = Modifier
                                .fillMaxWidth()
                                .heightIn(min = 200.dp)
                        )
                    } else {
                        Text(
                            text = chapter.content,
                            style = MaterialTheme.typography.bodyLarge.copy(
                                fontSize = 18.sp,
                                lineHeight = 32.sp
                            ),
                            textAlign = TextAlign.Justify,
                            modifier = Modifier.fillMaxWidth()
                        )
                    }
                }
            }
        }
        
        // 底部空白区域
        item {
            Spacer(modifier = Modifier.height(120.dp))
        }
    }
}

@Composable
fun TableOfContentsDialog(
    tocItems: List<TocItem>,
    onDismiss: () -> Unit,
    onTocItemClick: (String) -> Unit
) {
    AlertDialog(
        onDismissRequest = onDismiss,
        title = {
            Text(
                text = "目录",
                style = MaterialTheme.typography.headlineSmall,
                fontWeight = FontWeight.Bold
            )
        },
        text = {
            LazyColumn(
                modifier = Modifier.heightIn(max = 400.dp),
                verticalArrangement = Arrangement.spacedBy(4.dp)
            ) {
                items(tocItems.size) { index ->
                    val item = tocItems[index]
                    Card(
                        modifier = Modifier
                            .fillMaxWidth()
                            .clickable { onTocItemClick(item.href) },
                        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
                    ) {
                        Text(
                            text = item.title,
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(16.dp),
                            style = MaterialTheme.typography.bodyLarge
                        )
                    }
                }
            }
        },
        confirmButton = {
            TextButton(onClick = onDismiss) {
                Text("关闭")
            }
        }
    )
}

@Composable
fun BottomReadingToolbar(
    progress: Float,
    currentChapter: String,
    totalChapters: Int,
    onProgressChange: (Float) -> Unit,
    onPreviousChapter: () -> Unit,
    onNextChapter: () -> Unit,
    modifier: Modifier = Modifier
) {
    Surface(
        modifier = modifier.fillMaxWidth(),
        color = Color.Black.copy(alpha = 0.8f)
    ) {
        Column(
            modifier = Modifier.padding(16.dp)
        ) {
            // 当前章节信息
            if (currentChapter.isNotEmpty()) {
                Text(
                    text = currentChapter,
                    color = Color.White,
                    fontSize = 14.sp,
                    fontWeight = FontWeight.Medium,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis,
                    modifier = Modifier.padding(bottom = 8.dp)
                )
            }
            
            // 进度条
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = "${(progress * 100).toInt()}%",
                    color = Color.White,
                    fontSize = 12.sp,
                    modifier = Modifier.width(40.dp)
                )
                
                Slider(
                    value = progress,
                    onValueChange = onProgressChange,
                    modifier = Modifier.weight(1f),
                    colors = SliderDefaults.colors(
                        thumbColor = Color.White,
                        activeTrackColor = Color.White,
                        inactiveTrackColor = Color.White.copy(alpha = 0.3f)
                    )
                )
                
                Text(
                    text = "100%",
                    color = Color.White,
                    fontSize = 12.sp,
                    modifier = Modifier.width(40.dp),
                    textAlign = TextAlign.End
                )
            }
            
            Spacer(modifier = Modifier.height(8.dp))
            
            // 控制按钮
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceEvenly
            ) {
                TextButton(
                    onClick = onPreviousChapter,
                    colors = ButtonDefaults.textButtonColors(
                        contentColor = Color.White
                    )
                ) {
                    Text("上一章")
                }
                
                TextButton(
                    onClick = { /* TODO: 目录 */ },
                    colors = ButtonDefaults.textButtonColors(
                        contentColor = Color.White
                    )
                ) {
                    Text("目录 ($totalChapters)")
                }
                
                TextButton(
                    onClick = onNextChapter,
                    colors = ButtonDefaults.textButtonColors(
                        contentColor = Color.White
                    )
                ) {
                    Text("下一章")
                }
            }
        }
    }
}

@Composable
fun ReadingPageContent(
    bookContent: BookContent,
    chapterIndex: Int,
    modifier: Modifier = Modifier
) {
    if (chapterIndex >= bookContent.chapters.size) return
    
    val context = LocalContext.current
    val bookReader = remember { BookReader(context) }
    var loadedChapter by remember(chapterIndex) { mutableStateOf<Chapter?>(null) }
    var isLoadingChapter by remember(chapterIndex) { mutableStateOf(false) }
    
    val chapter = bookContent.chapters[chapterIndex]
    
    // 初始化章节内容
    LaunchedEffect(chapterIndex) {
        // 内容已经在BookReader中预处理，直接使用
        loadedChapter = chapter
        isLoadingChapter = false
    }
    
    val displayChapter = loadedChapter ?: chapter
    
    LazyColumn(
        modifier = modifier,
        contentPadding = PaddingValues(16.dp),
        verticalArrangement = Arrangement.spacedBy(16.dp)
    ) {
        // 书籍标题（仅在第一章显示）
        if (chapterIndex == 0) {
            item {
                Text(
                    text = bookContent.title,
                    style = MaterialTheme.typography.headlineLarge,
                    fontWeight = FontWeight.Bold,
                    textAlign = TextAlign.Center,
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(vertical = 24.dp),
                    color = MaterialTheme.colorScheme.primary
                )
            }
        }
        
        // 章节标题
        item {
            Text(
                text = displayChapter.title,
                style = MaterialTheme.typography.headlineMedium,
                fontWeight = FontWeight.Bold,
                textAlign = TextAlign.Center,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = 16.dp),
                color = MaterialTheme.colorScheme.primary
            )
        }
        
        // 章节内容 - 保持原文格式
        item {
            if (isLoadingChapter) {
                // 显示加载指示器
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(200.dp),
                    contentAlignment = Alignment.Center
                ) {
                    Column(
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        CircularProgressIndicator()
                        Spacer(modifier = Modifier.height(16.dp))
                        Text(
                            text = "正在加载章节内容...",
                            style = MaterialTheme.typography.bodyMedium,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    }
                }
            } else if (displayChapter.isHtml) {
                // 使用WebView渲染HTML内容，保持原文格式和图片
                AndroidView(
                    factory = { context ->
                        WebView(context).apply {
                            webViewClient = WebViewClient()
                            settings.apply {
                                javaScriptEnabled = false
                                loadWithOverviewMode = true
                                useWideViewPort = true
                                builtInZoomControls = false
                                displayZoomControls = false
                            }
                        }
                    },
                    update = { webView ->
                        val htmlContent = """
                            <!DOCTYPE html>
                            <html>
                            <head>
                                <meta charset="UTF-8">
                                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                                <style>
                                    body {
                                        font-family: serif;
                                        font-size: 18px;
                                        line-height: 1.8;
                                        margin: 16px;
                                        text-align: justify;
                                        color: #333;
                                        background-color: #fff;
                                    }
                                    img {
                                        max-width: 100%;
                                        height: auto;
                                        display: block;
                                        margin: 16px auto;
                                    }
                                    h1, h2, h3, h4, h5, h6 {
                                        text-align: center;
                                        margin: 24px 0 16px 0;
                                    }
                                    p {
                                        margin: 16px 0;
                                        text-indent: 2em;
                                    }
                                    /* PDF表格样式 */
                                    .pdf-table {
                                        width: 100%;
                                        border-collapse: collapse;
                                        margin: 16px 0;
                                        font-size: 16px;
                                    }
                                    .pdf-table th, .pdf-table td {
                                        border: 1px solid #ddd;
                                        padding: 8px 12px;
                                        text-align: left;
                                        vertical-align: top;
                                    }
                                    .pdf-table th {
                                        background-color: #f5f5f5;
                                        font-weight: bold;
                                        text-align: center;
                                    }
                                    .pdf-table tr:nth-child(even) {
                                        background-color: #f9f9f9;
                                    }
                                    .pdf-table tr:hover {
                                        background-color: #f0f0f0;
                                    }
                                    /* PDF内容容器 */
                                    .pdf-content {
                                        line-height: 1.6;
                                    }
                                    .pdf-content h3 {
                                        color: #2c3e50;
                                        margin: 20px 0 10px 0;
                                        font-size: 20px;
                                    }
                                </style>
                            </head>
                            <body>
                                ${displayChapter.content}
                            </body>
                            </html>
                        """.trimIndent()
                        webView.loadDataWithBaseURL(null, htmlContent, "text/html", "UTF-8", null)
                    },
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(600.dp)
                )
            } else {
                // 纯文本内容
                val paragraphs = displayChapter.content.split("\n\n").filter { it.isNotBlank() }
                
                Column(
                    verticalArrangement = Arrangement.spacedBy(16.dp)
                ) {
                    paragraphs.forEach { paragraph ->
                        Text(
                             text = paragraph.trim(),
                             style = MaterialTheme.typography.bodyLarge.copy(
                                 fontSize = 18.sp,
                                 lineHeight = 32.sp
                             ),
                             textAlign = TextAlign.Justify,
                             modifier = Modifier.fillMaxWidth()
                         )
                     }
                 }
             }
        }
        
        // 底部空白区域
        item {
            Spacer(modifier = Modifier.height(120.dp))
        }
    }
}

@Preview(showBackground = true)
@Composable
fun ReadingScreenPreview() {
    EsayReadTheme {
        // ReadingScreen() // 预览时无法提供NavController和Book，暂时注释
    }
}